package jpaperwork.web;


import jpaperwork.example.customer.Customer;
import static jpaperwork.example.customer.Customer.createTestCustomer;
import jpaperwork.meta.transformer.*;

import static org.hypirinha.html.AttributeFactory.*;
import static org.hypirinha.html.ElementFactory.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

import org.hypirinha.html.elements.Div;
import org.hypirinha.html.elements.Form;
import org.hypirinha.html.elements.Html;
import org.hypirinha.html.output.PrintAdapter;


public class DispatcherServlet extends HttpServlet {
    final Dispatcher dispatcher;

    public DispatcherServlet() {
        dispatcher = new Dispatcher();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        jpaperwork.meta.descriptor.Form exampleFormDescriptor = new BeanFormReflector().reflectClass(Customer.class);


        Map<String, String> requestMap = new HashMap();
        requestMap = request.getParameterMap();

        FormTransformer transformer = new FormTransformer(
                exampleFormDescriptor,
                new RequestFormReader(),
                new BeanFormBuilder()
        );

        Customer parsed = (Customer) transformer.transform(requestMap);


        transformer = new FormTransformer(exampleFormDescriptor, new BeanFormReader(), new HtmlBuilder());

        Div content = (Div) transformer.transform(parsed);

        Form form = form(action(""), method("post")).contains(content);
        form.button(type("submit"), name("__action__"), value("submit")).text("Submit");
        form.button(type("submit"), name("__action__"), value("me")).text("me");


        Html html = html();
        html.body().contains(form);
        new PrintAdapter().print(html, response.getOutputStream());

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Customer customer = createTestCustomer();

        jpaperwork.meta.descriptor.Form exampleFormDescriptor = new BeanFormReflector().reflectClass(Customer.class);

        FormTransformer transformer = new FormTransformer(exampleFormDescriptor, new BeanFormReader(), new HtmlBuilder());


        Div content = (Div) transformer.transform(customer);

        Form form = form(action(""), method("post")).contains(content);
        form.button(type("submit")).text("Submit");


        Html html = html();
        html.body().contains(form);
        new PrintAdapter().print(html, response.getOutputStream());
    }


}
